﻿using GatewayClient.Device;
using GatewayClient.Models;
using GatewayClient.Service;
using Iot.Device.Ads1115;
using Models.Common;
using MQTTnet.Client;
using MQTTnet.Protocol;
using NewLife.Caching.Queues;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using UtilsBase;
using UtilsCache;
using UtilsMQ;
using UtilsMQ.Model;

namespace GatewayClient.MQ
{
    public class ServiceMqttClient : MqttClientService
    {
        public ServiceMqttClient()
        {
            _topic = ConstantMqtt.gateway_topic + "_" + UtilAppsettingCache.getSetting("base:gatewayCode");
            ConstantMqtt.ip = UtilAppsettingCache.getSetting("mqtt:hostName");
            ConstantMqtt.port = int.Parse(UtilAppsettingCache.getSetting("mqtt:port"));
            ConstantMqtt.username = UtilAppsettingCache.getSetting("mqtt:userName");
            ConstantMqtt.password = UtilAppsettingCache.getSetting("mqtt:password");
        }

        public void start()
        {

            new ServiceMqttClient().MqttClientStart();


        }
        /// <summary>
        /// 收到消息事件
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        public override Task _mqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
        {
            //Console.WriteLine($"收到消息事件ApplicationMessageReceivedAsync：客户端ID=【{arg.ClientId}】接收到消息。Topic主题=【{arg.ApplicationMessage.Topic}】 消息=【{Encoding.UTF8.GetString(arg.ApplicationMessage.Payload)}】 qos等级=【{arg.ApplicationMessage.QualityOfServiceLevel}】");

            //这里不要新线程了，因为后面用到的handleEventLists线程不生效，跨线程用不了
            string message = Encoding.UTF8.GetString(arg.ApplicationMessage.PayloadSegment);
            Task.Run(() =>
            {
                new ServiceMQPayEvent().payEvent(message);
            });
            return Task.CompletedTask;
        }

        public bool sendMsg(string data)
        {
            return new MqttClientService().Publish(ConstantMqtt.gateway_server_topic, data);

        }
        public bool sendMsgRetain(string data)
        {
            return new MqttClientService().PublishRetain(ConstantMqtt.gateway_server_topic, data);

        }
    }
}
